/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.boot.starter.middleware.config;

import io.iec.edp.caf.boot.starter.middleware.entity.CAFErrorPageConfig;
import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.middleware.entity.CAFBootServerConfigurationProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.servlet.ConditionalOnMissingFilterBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.CacheControl;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * This is {@link CAFWebMvcConfigurer}.
 * 用于设置静态资源路径、静态资源的缓存方式
 *
 * @author yisiqi
 * @since 1.0.0
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({
		CAFBootServerConfigurationProperties.class,CAFErrorPageConfig.class
})
public class CAFWebMvcConfigurer implements WebMvcConfigurer {

	private final CAFBootServerConfigurationProperties properties;
	private String edpHomePath;

	public CAFWebMvcConfigurer(CAFBootServerConfigurationProperties properties) {
		this.properties = properties;
		this.edpHomePath = this.initEdpHomePath();
	}

	@Bean
	@ConditionalOnExpression("${caf-error-page.enabled}==true")
	public ErrorPageRegistrar errorPageRegistrar(){
		return new CAFErrorPageRegistrar();
	}

	@Override
	public void addViewControllers(ViewControllerRegistry registry){
		String path = properties.getHomePage();

		registry.addViewController("/").setViewName("forward:"+path);
		registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.html
		//Patterns such as "/static/**" or "/css/{filename:\\w+\\.css}" are supported.
		//https://stackoverflow.com/questions/31712535/prevent-caching-index-html-file-using-spring-boot
		List<URL> externalStaticRes = properties.getStaticResources().getExternalStaticResources();
		String[] locations = new String[0];
		if (!StringUtils.isEmpty(externalStaticRes)) {
			locations = externalStaticRes
					.stream()
					.map(
							url -> url
									.toString()
									.replaceAll("\\$EDP_HOME", this.edpHomePath)
									.replaceAll("([^/])$", "$1/")

					)
					.toArray(String[]::new);

		}

		//经验证，order数值大的话，优先级高，仅将html设置为no-cache
		registry.setOrder(100).addResourceHandler("/**/{filename:[\\s\\S]*\\.html}")
				.addResourceLocations(locations)
				.setCacheControl(CacheControl.maxAge(0, TimeUnit.SECONDS).mustRevalidate().cachePublic())
				.setCacheControl(CacheControl.noCache())
//				.setCacheControl(CacheControl.noStore())
				.resourceChain(true);

		//经验证，正则表达式不支持复杂嵌套的正则表达式，如假设匹配某一不以.jpg结尾的字符串 	^((?!\.jpg$).)*$
		ResourceHandlerRegistration registration = registry.setOrder(0).addResourceHandler("/**")
				.addResourceLocations(locations);
		if (properties.getStaticResources().getEnableCache()) {
			registration.setCachePeriod(properties.getStaticResources().getPeriodOfCacheInSeconds())
					.resourceChain(true);
		}
	}

	//todo 屏蔽WebMvcAutoConfiguration spring controller存在乱码，先不处理了
//	/**
//	 * 不加这个的话去除@WebMvcAutoConfiguration会获取不到RequestContextHolder中的session信息
//	 * todo RequestContextFilter是一个Servlet Filter，专门用来将当前请求绑定到当前线程
//	 * @return
//	 */
//	@Bean
//	@ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class })
//	@ConditionalOnMissingFilterBean(RequestContextFilter.class)
//	public static RequestContextFilter requestContextFilter() {
//		return new OrderedRequestContextFilter();
//	}


	private String initEdpHomePath(){
		String path = CafEnvironment.getServerRTPath();
		// Remove leading /.
		return path.replaceFirst("^/", "");
	}
}
